window.pageAction = (function() {

  var offer = function() {
    $('#pagecontent').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
    $('#pagecontent .preloader').show();
    
    var hash = location.hash.substr(1);
    var regexp = /offer([0-9]+)/i;
    if (regexp.test(hash)) {
      matches = hash.match(regexp);
      var offer_id = matches[1];
    }
            
    var reqData = {
			id: 1,
			on: 'OFFERS',
			'do': 'GET',
			data: {offer_id: offer_id}
		};
    $.ajax({
       type: "POST",
       url: lib.nodeapi,
       dataType: 'JSON',
       data:{msg: $.toJSON(reqData)},
       async: false,
       success: function(response) {
         if (response.result) {          
    			try {
    				var template = new EJS({url: '/ejs/offer.ejs'});
    				var result = template.render(response);
    			} catch(e) {			
    				return false;
    			}    			
          $('#pagecontent .preloader').remove();    
          $('#pagecontent').html(result);
         }
       }
    });
  } 

  var user = function() {
    $('#pagecontent').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
    $('#pagecontent .preloader').show();
    
    var hash = location.hash.substr(1);
    var regexp = /user([0-9]*)/i;
    if (regexp.test(hash)) {
      matches = hash.match(regexp);
      var user_id = matches[1];
    }
            
    var reqData = {
			id: 1,
			on: 'USER',
			'do': 'GET',
			data: {user_id: user_id}
		};
    $.ajax({
       type: "POST",
       url: lib.nodeapi,
       dataType: 'JSON',
       data:{msg: $.toJSON(reqData)},
       async: false,
       success: function(response) {
         if (response.result) {          
    			try {
    				var template = new EJS({url: '/ejs/user.ejs'});
    				var result = template.render(response);
    			} catch(e) {			
    				return false;
    			}    			
          $('#pagecontent .preloader').remove();    
          $('#pagecontent').html(result);                          
         }
       }
    });
  } 
 
  var ref = function() {
    var hash = 'ref';
    if (nav.userLogged) {
      location.hash = '#search';
    } else {
      $('#pagecontent').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
      $('#pagecontent .preloader').show();
      var reqData = {
  			id: 1,
  			on: 'USER',
  			'do': 'GET',
  			data: {user_id: lib.refid}
  		};
      $.ajax({
         type: "POST",
         url: lib.nodeapi,
         dataType: 'JSON',
         data:{msg: $.toJSON(reqData)},
         async: false,
         success: function(response) {
           if (response.result) {          
      			try {
      				var template = new EJS({url: '/ejs/ref.ejs'});
      				var result = template.render(response);
      			} catch(e) {			
      				return false;
      			}    			
            $('#pagecontent .preloader').remove();    
            $('#pagecontent').append(result);                          
           }
         }
      });			
    }
  }
 
  var catalog = function() {
    $('#pagecontent').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
    $('#pagecontent .preloader').show();
    var reqData = {
			id: 1,
			on: 'TAGS',
			'do': 'LIST',
			data: {
				type: "CAT_THEME"
			}
		};
    $.ajax({
       type: "POST",
       url: lib.nodeapi,
       dataType: 'JSON',
       data:{msg: $.toJSON(reqData)},
       async: false,
       success: function(response) {
         if (response.result) {          
    			try {
    				var template = new EJS({url: '/ejs/catalog.ejs'});
    				var result = template.render(response);
    			} catch(e) {			
    				return false;
    			}
          $('#pagecontent .preloader').remove();    
          $('#pagecontent').append(result);
                        
         }
       }
    }); 
  }
  
  var search = function() {
    if (!$('.pagecontent .map-container').length) {
      var data = {};
      var hash = 'search';
      $('#pagecontent').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
      $('#pagecontent .preloader').show();
  		try {
  			var template = new EJS({url: '/ejs/'+hash+'.ejs'});		
  			var result = template.render(data);
  		} catch(e) {
  			return false;
  		}        		
      $('#pagecontent .preloader').hide();    
      $('#pagecontent').html(result);
      lib.searchMapDrown = false;  
    }
    
    if (!lib.searchMapDrown) mapsearch.requestPosition();      
    $('.search-result_items').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
    $('.search-result_items .preloader').show();
    $('.recommendation-block').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
    $('.recommendation-block .preloader').show(); 
    
    var query = lib.getParameterByName('query');
    $('.popup-location_search .search_query').val(query);    
    $('.search-result_query').text(query);    
    
    if (mapsearch.userCenter.lon == null || mapsearch.userCenter.lat == null) {
      mapsearch.userCenter.lon = 44.00299072265625;
      mapsearch.userCenter.lat = 56.320636625218356; 
    }     
    
    setTimeout(function(){
    var reqData = {
        "id": 1,
        "on": "GEO",
        "do": "SEARCH",
        "data": {
          "center": [
            mapsearch.userCenter.lon,
            mapsearch.userCenter.lat
          ],
          "radius": 3000,
          "query": query
        }      
    };
    $.ajax({
       type: "POST",
       url: lib.nodeapi,
       dataType: 'JSON',
       data:{msg: $.toJSON(reqData)},
       async: false,
       success: function(response) {
          pageAction.searchHandle(response);  				
       }
    });      
    },100);
  }
  
  var index = function() {
    this.insertContent('index');			
  }
  
  var insertContent = function(hash) {
    var data = {};
    $('#pagecontent').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
    $('#pagecontent .preloader').show();
		try {
			var template = new EJS({url: '/ejs/'+hash+'.ejs'});		
			var result = template.render(data);
		} catch(e) {
			return false;
		}        		
    $('#pagecontent .preloader').hide();    
    $('#pagecontent').html(result);  
  }
  
  var profile = function() {
    if (!nav.userLogged) {location.hash='#search'; return;}  
    var hash = 'profile';
    $('#pagecontent').html('<div class="preloader"><img src="/css/images/preloader.gif" align="center"/></div>');
    $('#pagecontent .preloader').show();
    var reqData = {
			id: 1,
			on: 'USER',
			'do': 'GET',
			data: {}
		};
    $.ajax({
       type: "POST",
       url: lib.nodeapi,
       dataType: 'JSON',
       data:{msg: $.toJSON(reqData)},
       async: false,
       success: function(response) {
         if (response.result) {          
    			try {
    				var template = new EJS({url: '/ejs/profile.ejs'});
    				var result = template.render(response);
    			} catch(e) {			
    				return false;
    			}    			
          $('#pagecontent .preloader').remove();    
          $('#pagecontent').append(result);
                        
         }
       }
    });  
    //this.insertContent('profile');	
  }  
  
  var settings = function() {
    if (!nav.userLogged) {location.hash='#search'; return;}
    
    this.insertContent('settings');
    
    var reqData = {
      "id": 1,
      "on": "USER",
      "do": "GET",
      "data": {}
    };
    $.ajax({
      type: "POST",
      url: lib.nodeapi,
      dataType: 'JSON',
      data: {
        msg: $.toJSON(reqData)
      },
      async: false,
      success: function(response) {
        if (response.result == true) {
          $('#userSettingsForm [name=name]').val(response.data.user.name);
          $('#userSettingsForm [name=city_id]').val(response.data.user.city_id);
          $('#userSettingsForm [name=about]').val(response.data.user.about);
          $('#userSettingsForm [name=birthday]').val(response.data.user.birthday);
          $('#userSettingsForm [name=childs][value="'+response.data.user.childs+'"]').attr('checked','checked');
          $('#userSettingsForm [name=gender][value="'+response.data.user.gender+'"]').attr('checked','checked');
          var img = (response.data.user.fotofile==null)?'/css/images/profile.png':'/s3/foto/'+response.data.user.fotofile;
					$('#userSettingsForm #upload_img').attr('src', img);
					$('#userSettingsForm #upload_fileid').val(response.data.user.foto);
					$('#refLink').val('http://timebooka.com/#ref'+response.data.user.user_id);
          $('#suggestEmail').val(response.data.user.email);         
          $('#suggestPhone').val(response.data.user.phone);
          
          var input = document.getElementById('settingsCity');
          var options = {componentRestrictions: {country: 'ru'}};
          var autocomplete = new google.maps.places.Autocomplete(input,options);
        }        
      }
    });    
    
    $("#userSettingsForm .datepick").datepicker({format:'dd.mm.yyyy'});        
  }  
  
  var dialogs = function() {
    this.insertContent('dialogs');
  }  
  
  var getmoney = function() {
    this.insertContent('getmoney');			
  }  
  
  var about = function() {
    this.insertContent('about');			
  }  

  var help = function() {
    this.insertContent('help');			
  }
  
  var offerform = function() {
    this.insertContent('offerform');
    $(".datepick").datepicker({format:'dd.mm.yyyy'});    
  }
  
  var searchHandle = function(response) {
    mapsearch.initialize_edit(mapsearch.userCenter.lat, mapsearch.userCenter.lon);
  	if (response.result == true){
			for(var i in response.data){
				var d = response.data[i];				
				switch(d.geo.type){
					case 'POINT': {
						if(d.user && d.user.fotofile){
							mapsearch.drawGeoJSON(d.geo.center, {
								icon: {
									url: '/s3/foto/'+d.user.fotofile,
									size: {
										width: 40,
										height: 40
									},
									scaledSize: {
										width: 40,
										height: 40
									}
								},
								title: d.user.name ? d.user.name : ('Юзер №'+d.user.user_id)
							});
						} else {
							mapsearch.drawGeoJSON(d.geo.geojson);
						}
					} break;
					
					case 'POLYGON': {
    				/*var myPolygonOptions = {
    					fillColor: '#ff0000',
    					fillOpacity: 0.2,
    					strokeColor: '#ff0000',
    					strokeOpacity: 0.5,
    					strokeWeight: 2
    				};                  									
						mapsearch.drawGeoJSON(d.geo.geojson, myPolygonOptions);*/
						if(d.user && d.user.fotofile){						
							mapsearch.drawGeoJSON(d.geo.center, {
								icon: {
									url: '/s3/foto/'+d.user.fotofile,
									size: {
										width: 40,
										height: 40
									},
									scaledSize: {
										width: 40,
										height: 40
									}
								},
								title: d.user.name ? d.user.name : ('Юзер №'+d.user.user_id)
							});
						} else {
							mapsearch.drawGeoJSON(d.geo.center);
						}
					} break;
				}
			}
    }  		     				
		try {
			var template1 = new EJS({url: '/ejs/search-result-item.ejs'});
			var template2 = new EJS({url: '/ejs/recommendation-block.ejs'});
			var result1 = template1.render(response);
			var result2 = template2.render(response);
		} catch(e) {			
			return false;
		}		
    $('.search-result_items .preloader').hide();    
    $('.search-result_items').html(result1);    
    
    $('.recommendation-block .preloader').hide();    
    $('.recommendation-block').html(result2);
    var datalen = 0;
    if (typeof response.data.length != 'undefined') datalen = response.data.length;    
    $('#searchNearCount').text(datalen);    
    $('#searchTotalCount').text((datalen<100?datalen:'>100'));    
    if (response.result == true){
      $(".down-icon").fadeIn(1000, function () {$(".down-icon").fadeOut(1000, function () {$(".down-icon").fadeIn(1000, function () {$(".down-icon").fadeOut(1000, function () {$(".down-icon").fadeIn(1000, function () {$(".down-icon").fadeOut(1000)})})})})});
    }
  }              
    
  return {
    insertContent: insertContent,
    catalog: catalog,
    search: search,
    index: index,
    settings: settings,
    getmoney: getmoney,
    about: about,
    help: help,
    dialogs: dialogs,
    profile: profile,
    offerform: offerform,
    ref: ref,
    searchHandle: searchHandle, 
    user: user,
    offer: offer
  };
})(jQuery);
